
# include "dfxEditor.h"

# pragma comment(lib, "../Debug/DFXEngine.lib")

namespace DFX
{
    Editor::Editor(const String &pluginPath)
        : mPluginPath(pluginPath),
        mCorePlugin(NULL),
        mGraphicsPlugin(NULL),        
        mGraphicsDevice(NULL),
        mClearColor(0.5f)
    {
        memset(mWindow, 0, sizeof(mWindow));
    }

    Editor::~Editor()
    {
        Destroy();
    }

    DFXRESULT Editor::Initialize(const std::vector<WINDOW_PARAMETERS*> params)
    {
        mLog = new FileLog((UInt32)LOG_TYPE_INFO);

        if (DFX_FAILED(mLog->Open("dfxEditor.log")))
        {
            fprintf(stderr, "ERROR- Unable to open log file");
            return DFX_INITFAILED;
        }

        mCorePlugin = new CorePlugin(mPluginPath + "/DFXWin32.dll");

        if (DFX_FAILED(mCorePlugin->Load()))
        {
            DFX_ERROR("Unable to load core plugin");
            return DFX_INITFAILED;
        }

        mGraphicsPlugin = new GraphicsPlugin(mPluginPath + "/DFXOpenGL.dll");

        if (DFX_FAILED(mGraphicsPlugin->Load()))
        {
            DFX_ERROR("Unable to load graphics plugin");
            return DFX_INITFAILED;
        }

        for (UInt32 i = 0; i < NUM_WINDOWS; i++)
        {
            mCorePlugin->WindowCreate("EditorWindow", "EditorClass", &mWindow[i]);

            if (DFX_FAILED(mWindow[i]->Create(params[i])))
            {
                DFX_ERROR("Unable to create window from parameter");
                return DFX_INITFAILED;
            }
        }
                
        mGraphicsPlugin->CreateGraphicsDevice(&mGraphicsDevice);

        if (DFX_FAILED(mGraphicsDevice->Initialize(mWindow[0])))
        {
            DFX_ERROR("Unable to initialize graphics device");
            return DFX_INITFAILED;
        }

        for (UInt32 i = 1; i < NUM_WINDOWS; i++)
        {
            if (DFX_FAILED(mGraphicsDevice->CreateAdditional(mWindow[i])))
            {
                DFX_ERROR("Unable to create additional window: %d", i);
                return DFX_INITFAILED;
            }
        }

        return DFX_SUCCESS;
    }

    DFXRESULT Editor::Destroy()
    {
        SAFE_DELETE(mGraphicsDevice);        

        for (UInt32 i = 0; i < NUM_WINDOWS; i++)
            SAFE_DELETE(mWindow[i]);
        
        SAFE_DELETE(mGraphicsPlugin);
        SAFE_DELETE(mCorePlugin);
        SAFE_DELETE(mLog);

        return DFX_SUCCESS;
    }

    void Editor::Render(UInt32 index)
    {        
        mGraphicsDevice->SetCurrent(mWindow[index]);
        mGraphicsDevice->Clear(CLEAR_FLAGS_TARGET | CLEAR_FLAGS_DEPTH, mClearColor);        
    }
}